/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2022-03-11 16:00
**/
package jaeger

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"ydd-im/config"
	"ydd-im/util/interceptor/jaegerinterceptor"
)

func SetUp() gin.HandlerFunc {

	return func(c *gin.Context) {
		cfg := config.GetJaggerConfig()
		tracer, closer,err := jaegerinterceptor.NewJaegerTracer(cfg.Name, cfg.Endpoint)
		if err != nil {
			panic(fmt.Sprintf("初始化失败%v",err))
		}
		defer closer.Close()
		var parentSpan opentracing.Span

		spCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))
		if err != nil {
			parentSpan = tracer.StartSpan(c.Request.URL.Path)
			defer parentSpan.Finish()
		} else {
			parentSpan = opentracing.StartSpan(
				c.Request.URL.Path,
				opentracing.ChildOf(spCtx),
				opentracing.Tag{Key: string(ext.Component), Value: "HTTP"},
				ext.SpanKindRPCServer,
			)
			defer parentSpan.Finish()
		}

		c.Set("Tracer", tracer)
		c.Set("ParentSpanContext", parentSpan.Context())

		c.Next()
	}
}
